package name.wilbur.course.db.bigone.service.impl;

import java.util.ArrayList;
import java.util.List;

import name.wilbur.course.db.bigone.dao.DAOFactory;
import name.wilbur.course.db.bigone.dao.impl.FriendDAO;
import name.wilbur.course.db.bigone.dao.impl.IFriendDAO;
import name.wilbur.course.db.bigone.dao.impl.IUserDAO;
import name.wilbur.course.db.bigone.dao.impl.UserDAO;
import name.wilbur.course.db.bigone.model.Friend;
import name.wilbur.course.db.bigone.model.User;
import name.wilbur.course.db.bigone.service.IFriendService;

import org.apache.commons.collections.CollectionUtils;

public class FriendService implements IFriendService {
	private IFriendDAO friendDAO;
	private IUserDAO userDAO;
	
	public FriendService() {
	}
	
	public boolean addNewFriend(User user, int newID) {
		if (user.getPk() == newID)
			return false;
		return getFriendDAO().create(new Friend(user.getPk(), newID));
	}
	
	@Override
	public boolean addNewFriend(User user, List<User> friends, int newID) {
		if (user.getPk() == newID)
			return false;
		
		for (User u : friends)
			if (u.getPk() == newID)
				return false;
		
		friends.add((User) getUserDAO().findByPK(newID));
		return getFriendDAO().create(new Friend(user.getPk(), newID));
	}
	
	public boolean removeFriend(int myID, int friendID) {
		return getFriendDAO().deleteFriend(myID, friendID);
	}
	
	@Override
	public List<User> findMyFriends(int id) {
		List<User> friends = new ArrayList<User>();
		User[] friendUsers = getFriendDAO().findFriends(id);
		if (friendUsers != null)
			CollectionUtils.addAll(friends, friendUsers);
		return friends;
	}
	
	public IUserDAO getUserDAO() {
		if (userDAO == null)
			userDAO = (UserDAO) DAOFactory.createDAO(UserDAO.class);
		return userDAO;
	}
	public IFriendDAO getFriendDAO() {
		if (friendDAO == null)
			friendDAO = (FriendDAO) DAOFactory.createDAO(FriendDAO.class);
		return friendDAO;
	}
}
